package com.aigou.admin.controller;

import com.aigou.admin.entity.Product;
import com.aigou.admin.service.ProductService;
import com.aigou.admin.service.impl.ProductServiceImpl;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * 保存商品的Servlet
 */
@WebServlet("/saveProduct")
public class SaveProductController extends HttpServlet {

    // 调用service
    private ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码为UTF-8
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json; charset=UTF-8");

        // 获得商品信息
        String id = req.getParameter("id");
        String productName = req.getParameter("productName");
        String productImage = req.getParameter("productImage");
        double price = Double.parseDouble(req.getParameter("price"));
        String productType = req.getParameter("productType");
        String productDesc = req.getParameter("productDesc");
        Timestamp createTime = new Timestamp(System.currentTimeMillis()); // 当前时间
        String productBrand = req.getParameter("productBrand");

        Product product = new Product(id, productName, productImage, price, productType, productDesc, createTime, productBrand);

        // 保存商品
        int result = productService.addProduct(product);

        // 转换为JSON,通过流发送给客户端
        JSONObject responseJson = new JSONObject();
        responseJson.put("status", result > 0 ? "success" : "failure");
        responseJson.put("message", result > 0 ? "Product saved successfully" : "Failed to save product");
        resp.getWriter().write(responseJson.toJSONString());
    }
}
